package com.example.springbootrbac.handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

@Component
public class SecurityPermissionEvaluatorHandler implements PermissionEvaluator {
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private AntPathMatcher antPathMatcher;

    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        // 循环所有的权限，并且根据uri路径验证是否有权限
        for (GrantedAuthority authority : authentication.getAuthorities()) {
            if(antPathMatcher.match(request.getRequestURI(),authority.getAuthority())){
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        return false;
    }
}
